import time
import db
import os
import configparser
import json
import requests

# 读取配置文件  必须重启服务才可以重新加载
config_path = os.path.split(os.path.realpath(__file__))[0]
config = configparser.RawConfigParser()
config.read(config_path+'\config.ini', encoding="utf-8-sig")


class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


class wind():

    def __init__(self):
        # print('__init__')
        self.dbconn = db.db()

        # print(self.dbconn)
        # pass

# ====================================初始化需要配置的参数下==============================


    #读取全部的配置信息
    def allConfig(self):
        return config

    #通常用来判断当前是否为跑服务的时间 传入开始和结束时间  如果是工作日  且当前时间在开始和结束时间当中 则返回true 否则返回false
    #@param 传入的时间格式 xx:xx:xx
    #@ runtype  服务跑的类型  1仅在交易日跑  2每天都跑
    def runTime(self,start='09:20:00',end='15:35:00',runtype = 1):
        try:
            flag = False

            now = time.strftime("%Y-%m-%d %H:%M:%S")
            # 0为日期  1为时间  ['2019-05-27', '17:51:15']
            nowArr = now.split(' ')

            resTran = 1


            if nowArr[1] >= start and nowArr[1] <= end and resTran >0:
                flag = True

            return flag
        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)

    # 异常日志
    def logAbnormal(self, type, server_display_name, server_description, file, line, remark=None):
        try:
            file = file.replace('\\','/')

            if remark is not None:
                tmp_remark = str(remark)
                tmp_remark = tmp_remark.replace("'",' ')
                tmp_remark = tmp_remark.replace('"',' ')

            sql = 'insert into tb_log_server_abnormal(`type`,server_display_name,server_description,file,line,remark) ' \
                  'values({},"{}","{}","{}",{},"{}")'.format(type, server_display_name, server_description, file, line,
                                                             tmp_remark)

            print(sql)
            self.dbconn.opt_one(sql)
        except Exception as e:
            print('无法写入异常日志，：{}',e)
            pass



    # 运行日志
    def logRun(self, type, server_display_name, server_description, remark=None):
        try:

            sql = 'insert into tb_log_server_run(`type`,server_display_name,server_description,remark) ' \
                  'values({},"{}","{}","{}")'.format(type, server_display_name, server_description, remark)
            self.dbconn.opt_one(sql)

        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)


    # 实用日志
    def logPractical(self, type, server_display_name, server_description, remark=None,return_content=None):
        try:

            sql = "insert into tb_log_server_practical(`type`,server_display_name,server_description,remark,return_content) " \
                  "values({},'{}','{}','{}','{}')".format(type, server_display_name, server_description, remark,return_content)

            self.dbconn.opt_one(sql)

        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)


    # 发送数据到远程接口
    def remoteApi(self, arr ,url):

        try:

            post_arr = {
                'param': arr
            }

            # # json后的数据
            # json_data = json.dumps(post_arr, cls=DecimalEncoder, separators=(',', ':'))
            #
            # # 加密后的数据
            # encrypt_data = obj_aes.encrypt(json_data)

            # 插入发送日志
            # sql = """insert into tb_log_api(`serial`,send_receive,content_encrypt,content_decrypt,time_create,scene)
            #       values('{}','{}','{}','{}','{}','{}')
            #       """.format(serial, 1, encrypt_data, json_data, time_now, scene)
            #
            # lastid = self.dbconn.opt_one(sql)['data']

            # 发送到远程端口
            headers = {'Content-Type': 'application/json'}
            response = requests.post(url=config['remote_config']['device_url'] + url,
                                     headers=headers, data=post_arr)

            response_content = response.content.decode('utf-8')

            print(response_content)

            # return response_decrypt
        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"],
                             e.__traceback__.tb_lineno, e)




    #手动关闭数据库连接
    def dbclose(self):

        self.dbconn.dbclose()
